﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using MMOEng.Components;

namespace MMOEng.SubSystems
{
    public abstract class BaseSubSystem<T> : ISubSystem
    {
        protected MMOGame game;
        protected Dictionary<long, T> componentStore;

        public BaseSubSystem(MMOGame game)
        {
            this.game = game;
            this.componentStore = new Dictionary<long, T>();
            this.RegisterComponent();
        }

        public void AddComponent(guid entity, T component)
        {
            if (componentStore.ContainsKey(entity.ID))
                throw new InvalidOperationException("Can not readd a component to a subsystem");
            componentStore.Add(entity.ID, component);
        }

        public T GetComponent(guid entity){
            if(!componentStore.ContainsKey(entity.ID))
                throw new InvalidOperationException("Trying to get a component from a subsystem that has no knowledge of the component");
            return componentStore[entity.ID];
        }

        public void RemoveComponent(guid entity)
        {
            if (!componentStore.ContainsKey(entity.ID))
                throw new InvalidOperationException("Cannot remove a component that doesn't exist in a subsystem");
            componentStore.Remove(entity.ID);
        }

        public abstract void UpdateComponent(BaseComponent component);

        public void PostUpdate(Packets.EnginePackets.DeltaUpdateP updatePacket)
        {
            game.NetworkManager.WritePacket(updatePacket);
        }

        public abstract void RegisterComponent();
        public abstract void Update(GameTime gameTime);
        public abstract void Draw(GameTime gameTime);
        public abstract void LoadContent();
    }
}
